(ns ura.data.AuthInfo
  (:require
   [taoensso.telemere :as t]
   [ura.data.Data :refer [executeSql checkDataNull upcaseKey]]
   )
  (:use tupelo.core)
  )


(defn queryAuthById [id]
  (executeSql {:select [:*]
                  :from :AUTH_INFO
                  :where [:= :ID id]})
  )


(defn queryAuthByCode [code]
  (executeSql {:select [:*]
                  :from :AUTH_INFO
                  :where [:= :CODE code]})
  )


(defn queryAuthInfo "查询信息"
  [params]
  (t/log! ["query auth by: " params])
  (let [name (:name params)
        category (:category params)
        code (:code params)
        ]
    (executeSql {:select [:*]
                    :from [:AUTH_INFO]
                    :where [:and
                            (when (checkDataNull name) [:like :NAME (str "%" name "%")])
                            (when (checkDataNull category) [:like :CATEGORY (str "%" category "%")])
                            (when (checkDataNull code) [:like :CODE (str "%" code "%")])
                            ]
                    })
    )
  )


(defn updateAuthInfo [authInfoData]
  (t/log! ["get update auth request: " authInfoData])
  (let [id (:id authInfoData)
        auth (upcaseKey (select-keys authInfoData [:name :category :code :description :state]))
        ]    
    (executeSql {:update :AUTH_INFO
                    :set auth
                    :where [:= :ID id]
                    })
    )
  )

(defn insertData [authInfoData]
  (let [
        newId {:id :AUTH_INFO_SEQ/nextval}
        authInfo (select-keys authInfoData [:name :category :code :description :state])
        values (upcaseKey (merge authInfo newId))
        ]
    (executeSql {:insert-into [:AUTH_INFO]
                    :values [values]
                    })
    )
  )

(defn saveAuthInfo [authInfoData]
  (t/log! ["get save auth request: " authInfoData])
  (let [isExist (first (queryAuthById (:id authInfoData)))]
    (if isExist
      (updateAuthInfo authInfoData)
      (insertData authInfoData)
      )
    )
  )


(defn deleteAuthInfo [id]
  (t/log!  ["delete authInfo by id: " id])
  (executeSql {:delete-from [:AUTH_INFO]
                  :where [:= :ID id]
                  })
  )
